package com.fl.mybatisgenerator.thread;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import javax.xml.ws.Service;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.*;

/**
 * 出租车接客demo
 */
@Slf4j
public class excutorService {
    @SneakyThrows
    @Test
    public void test() {
        ExecutorService service = Executors.newCachedThreadPool();
        ArrayList<Future<String>> futures = new ArrayList<>();
        System.out.println("开始接送乘客");
        Task task = (i,time)->{
            Future<String> future = service.submit(() -> {
                log.info("乘客{}将在{}分钟后到达约定地点",i,time);
                TimeUnit.SECONDS.sleep(time);
//                log.info("乘客{}已到达约定地点",i);
                return "乘客:"+i+"已到达约定地点";
            });
            return future;
        };
        Random r1 = new Random();
        for (int i = 0; i < 10; i++) {
            Future<String> future = task.taskStart(r1.nextInt(10), r1.nextInt(20));
            futures.add(future);
        }
        TimeUnit.SECONDS.sleep(2);
        log.info("乘客行程已全部通知");
        for (Future<String> future : futures) {
            String info = future.get();
            log.info("{}，请前去接他",info);
        }
        Thread.currentThread().join();
//        service.shutdown();
    }
}

interface Task {
    Future<String> taskStart(Integer i,Integer time);
}
@Slf4j
class excutorService2{
    @SneakyThrows
    @Test
    public void test() {
        ExecutorService service = Executors.newCachedThreadPool();
        ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(service);
        System.out.println("开始接送乘客");
        Task task = (i,time)->{
            Future<String> future = completionService.submit(() -> {
                log.info("乘客{}将在{}分钟后到达约定地点",i,time);
                TimeUnit.SECONDS.sleep(time);
                return "乘客:"+i+"已到达约定地点";
            });
            return future;
        };
        Random r1 = new Random();
        for (int i = 0; i < 5; i++) {
            Future<String> future = task.taskStart(r1.nextInt(100), r1.nextInt(20));
        }
        TimeUnit.SECONDS.sleep(2);
        log.info("乘客行程已全部通知");
        for (int i = 0; i < 10; i++) {
            String info = completionService.take().get();
            log.info("{}，请前去接他",info);
            if (i==9){
                service.shutdown();
                log.info("线程停止");
                break;
            }
        }
        Thread.currentThread().join();
    }
}